/*
 *  File : URLEntryDAO.java
 *  Created By : madhurt
 *  Created On : Oct 27, 2010
 *  Yahoo! 2010
 */
package com.gebogebo.ds;

import com.gebogebo.URLEntry;
import com.google.appengine.api.datastore.Link;
import java.util.List;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author madhurt
 */
public class URLEntryDAO {

    public URLEntry getURLEntry(String shortCode) {
        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            URLEntry urlEntry = pm.getObjectById(URLEntry.class, shortCode);
            return urlEntry;
        } catch (JDOObjectNotFoundException ex) {
            return null;
        }
    }

    public URLEntry getURLEntryForLongURL(String longURLToSearch) {
        if(longURLToSearch == null) {
            return null;
        }
        
        PersistenceManager pm = PMF.get().getPersistenceManager();

        Link longLink = new Link(longURLToSearch);

        Query query = pm.newQuery(URLEntry.class);
        query.setFilter("longUrl == longUrlParam");
        query.declareParameters("com.google.appengine.api.datastore.Link longUrlParam");

        List<URLEntry> entries = (List<URLEntry>) query.execute(longLink);

        if (entries == null || entries.isEmpty()) {
            return null;
        }

        return entries.get(0);
    }
}
